package top.blackcat.learn.shiro.handler;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.blackcat.learn.shiro.enums.RedisKeyEnum;
import top.blackcat.learn.shiro.exception.ExceptionRes.ApiError;
import top.blackcat.learn.shiro.exception.ServiceException;
import top.blackcat.learn.shiro.utils.JWTUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class JWTHandler extends HandlerInterceptorAdapter {

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServiceException {
        HttpServletRequest req = request;
        String URI = req.getRequestURI();
        String token = req.getHeader("authToken");
        try {
            String key = String.format(RedisKeyEnum.USER_TOKEN.getMsg(), token);
            String jwtToken = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isBlank(jwtToken)) {
                log.info("token已过期！");
                throw new ServiceException(ApiError.ERROR_40000001);
            }
            // 校验 token
            DecodedJWT decodedJwt = jwtUtils.verify(jwtToken);
            if (decodedJwt == null) {
                log.error("token异常.........");
                throw new ServiceException(ApiError.ERROR_40000002);
            } else {
                log.info("验证成功.........");
                return true;
            }
        } catch (TokenExpiredException e) {
            log.error("异常.........");
            throw new ServiceException(ApiError.ERROR_40000001);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

//    public boolean checkAuth(String token, String URI) {
//        List<String> privList = userService.getPrivListByName(jwtUtils.get(token, "username"));
//        // 权限 列表
//        for (String priv : privList) {
//            if (URI.equals(priv)) {
//                // 有权限 更新访问时间 通过验证
//                stringRedisTemplate.opsForValue().getOperations().delete(token + "-reflushDate");
//                stringRedisTemplate.opsForValue().set(token + "-reflushDate", System.currentTimeMillis() + "");
//                return true;
//            }
//        }
//        return false;
//    }

}
